<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/04/28
 */
namespace api\modules\v1\controllers;

use common\logic\Boat;
use common\logic\Contact;
use common\models\Contact as ContactModel;
use Yii;
use yii\validators\Validator;
use yii\web\Controller;
use yii\web\Response;

class ContactController extends Controller {
    public $enableCsrfValidation = false;

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function actionIndex() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                '未登录'
            ];
        }
        /** @var \api\models\User $user */
        $user = Yii::$app->user->getIdentity();
        $method = Yii::$app->request->getMethod();
        if ($method == 'POST') {
            $r=Contact::saveContacts($user->id, [Yii::$app->request->post()]);
            if($r['err']!=0){
                return ['code'=>401,'msg'=>$r['msg']];
            }
        } elseif ($method == 'DELETE') {
            $id = Yii::$app->request->get('id');
            if (empty($id)) {
                return [
                    'code' => 401,
                    'msg'=>'参数错误',
                ];
            }
            Contact::deleteContact($user->id, [$id]);
        }
        return ['code' => 200];
    }

    public function actionList() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                '未登录'
            ];
        }
        $id=Yii::$app->request->get('id');
        /** @var \api\models\User $user */
        $user = Yii::$app->user->getIdentity();
        $res = Contact::getContactList($user->id, $id);
        $list = [];
        foreach ($res as $k => $v) {
            $list[] = [
                "id" => $v['id'],
                "name" => $v['name'],
                "gender" => (int)$v['gender'],
                "phone" => $v['phone'],
                "email" => $v['email'],
                "birthday" => $v['birthday']
            ];
        }
        return [
            'code' => 200,
            'data' => [
                'list' => $list,
            ],
        ];
    }
}
